import {Component, ViewChild} from '@angular/core';
import {NavController, NavParams, LoadingController,AlertController,Platform} from 'ionic-angular';

import _ from 'lodash';
import moment from 'moment';

import {FtMenu} from '../../ft-comp/ft-menu';

import {conf} from '../../config';
import {Backend} from '../../providers/backend';

import {EventKindPipe} from '../../pipes/pipes';

import {TabUpcomingInfo} from './tab-upcomingInfo';
import {TabPreviousInfo} from './tab-previousInfo';
import {TabsuveryInfo} from './tab-suveryInfo';
@Component({
  templateUrl: 'build/pages/tab-events/tab-events.html',
  directives: [FtMenu],
  pipes: [EventKindPipe],
  queries: {
    content: new ViewChild('content'),
  }
})
export class TabEvents {

  static get parameters() {
    return [[NavController], [NavParams], [Backend], [LoadingController],[AlertController],[Platform]];
  }

  constructor(nav, params, backend, loadingController,alertController,platform) {
    this.nav = nav;
    this.platform = platform;
    this.params = params;
    this.backend = backend;
    this.loadingController = loadingController;
    this.alertCtrl=alertController;
    this.viewMode;
    this.ban1;
    this.ban2;
    this.isAndroid;
    this.menus = [
      { 'id': '1', 'name': 'Upcoming Events' },
      { 'id': '2', 'name': 'Previous Events' },
      { 'id': '3', 'name': 'Survey' }
    ];
    console.log(this.platform.is('android'),66666,this.ban1);
    if (this.platform.is('android')) {
      this.isAndroid = true;
    }else if(this.platform.is('ios')){
      this.isAndroid = false;
    }
  }

  // 加载时间线事件
  loadTimeLine(id) {

    this.viewMode = 1;
    this.eventsByMonth = null;
    this.content.scrollToTop();

    // let loading = this.loadingController.create({
    //   content: 'loding ...'
    // });
    // loading.present();

    let timeOrder = 'asc';
    var date = '1900-01-01';
    var ssq;
    if (id == 2) {
      timeOrder = 'desc';
        date = new Date();
        date=date.getFullYear()+'-01-01';
        ssq='and e.timeBegin >';
        console.log(date,'5656');
    }
    console.log(date,'7878');
    this.backend.dsQuery({
      entity: 'gtig$TimelineEvent',
      viewName: 'timelineEvent-list',
      query: `select e from gtig$TimelineEvent e where e.state=${id} and e.timeBegin > '${date}' order by e.timeBegin ${timeOrder} `,
      first: 0,
      max: conf.pageSize
    }).then((result) => {
      // if(id == 1){
         let eventsByMonth = _.chain(result).each((item) => {
        let timeBegin = moment(item.timeBegin);
         item.year = timeBegin.format('YYYY');
        item.month = timeBegin.format('MMM');
        item.dayBegin = timeBegin.format('Do');
        item.dayFinish = moment(item.timeFinish).format('Do');
        // console.log(result,'5656');
        item.yearMonth = timeBegin.format('YYYYMM');
      }).groupBy('yearMonth').map((item) => {
        return { month: item[0].month,year: item[0].year, events: item };
      }).value();
      // console.log(eventsByMonth,'kaishi');
     
      if(id==2){
        for(let q=0;q<eventsByMonth.length;q++){
           for(let i=0;i<=eventsByMonth[q].events.length-1;i++){
              // console.log(eventsByMonth,'jinlaile1');
            for(let j=i+1;j<eventsByMonth[q].events.length;j++){
              //  console.log(eventsByMonth[q].events[i],eventsByMonth[q].events[j],'jinlaile ');
              if(eventsByMonth[q].events[i].sort>eventsByMonth[q].events[j].sort){
                let temp =eventsByMonth[q].events[i];   
                eventsByMonth[q].events[i] =eventsByMonth[q].events[j];  
                //  console.log(eventsByMonth[q].events[i],eventsByMonth[q].events[j],'jieshu561'); 
                eventsByMonth[q].events[j] = temp; 
              }
            }
        }
      }
      this.eventsByMonth = eventsByMonth;
      // console.log(eventsByMonth,'jieshu');
      }else{
        this.eventsByMonth = eventsByMonth;
      }
      
      // }else{
      //    let eventsByMonth = _.chain(result).each((item) => {
      //   let timeBegin = moment(item.timeBegin);
      //    item.year = timeBegin.format('YYYY');
      //   item.month = timeBegin.format('MMM');
      //   item.dayBegin = timeBegin.format('Do');
      //   item.dayFinish = moment(item.timeFinish).format('Do');
      //   console.log(result,'5656');
      //   item.yearMonth = timeBegin.format('YYYYMM');
        
      // }).groupBy('yearMonth').map((item) => {
      //   return { month: item[0].month,year: item[0].year, events: item };
      // }).value();
      // console.log(eventsByMonth,'5656');
      // this.eventsByMonth = eventsByMonth;
      // }
     

      // loading.dismiss();
    });
     this.backend.dsQuery({
      entity: 'gtig$SetVersion',
      viewName: '_local',
      query: `select e from gtig$SetVersion e `,
      first: 0,
      max: 1
    }).then((result1) => {
      
      this.ban1=result1[0].currentVersion;
      console.log(result1,88888,this.ban1);
      
      // .then(result => {
        
        this.ban2=conf.version;
        console.log(this.ban2,999,this.ban2);
        if(this.ban1 != this.ban2){
          let alert = this.alertCtrl.create({
                title: 'New version of GTI app is available now. ',
                
                buttons: [{
         text: 'Download',
         
         handler: () =>{
           
           if(this.isAndroid){
             var timestamp = Date.parse(new Date()); 
            //  cordova.InAppBrowser.open(result1[0].androidUrl, '_system', 'location=no');
            console.log(result1[0].androidUrl+timestamp); 
            this.backend.fileDownload(result1[0].androidUrl+timestamp);
           }else if(!this.isAndroid){
            //  cordova.InAppBrowser.open(result1[0].iosUrl, '_system', 'location=no'); 
            this.backend.fileDownload(result1[0].iosUrl);
           }
          
         }
       },{
         text: 'Cancel',
         
         buttons: ['CLOSE']
       }]
              });
              alert.present();
        }

      // });
      // loading.dismiss();
    });
  }

  loadSuvery() {
    
    this.backend.loadSuvery()
      .then(result => {
        this.suvery=_.values(result.result);
        
      });
  }

  menuChanged(menuItem) {
    if (menuItem.id == 1 || menuItem.id == 2) {
      this.viewMode = 1;
      this.loadTimeLine(menuItem.id);
    } else {
      this.viewMode = 2;
      this.loadSuvery();
    }
  }

  eventSelect(eventItem) {
    console.log(eventItem);
    
    if (eventItem.state == 1) {
      this.nav.rootNav.push(TabUpcomingInfo, { item: eventItem });
    } else {
      this.nav.rootNav.push(TabPreviousInfo, { item: eventItem });
    }
  }



  toSuvery(id) {
    this.nav.push(TabsuveryInfo,{id:id});
  }

}
